/*******************************************************************************
 * Copyright (c) 2012 rmateus.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 ******************************************************************************/
package com.yeook.ymax.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.yeook.ymax.app.ApplicationYMAX;

public class NetworkUtils {


	private static int TIME_OUT = 30000;


	@SuppressLint("NewApi")
	public BufferedInputStream getInputStream(String url, String username, String password, Context mctx) throws IOException{

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

        if(username!=null && password!=null){
			String basicAuth = "Basic " + new String(Base64.encode((username+":"+password).getBytes(),Base64.NO_WRAP ));
			connection.setRequestProperty ("Authorization", basicAuth);
		}
        connection.setConnectTimeout(TIME_OUT);
        connection.setReadTimeout(TIME_OUT);
		//connection.setRequestProperty("User-Agent", getUserAgentString(mctx));
        //System.out.println("Using user-agent: " + (getUserAgentString(mctx)));
		BufferedInputStream bis = new BufferedInputStream(connection.getInputStream(), 8 * 1024);

//		if(ApplicationAptoide.DEBUG_MODE)
        Log.i("Aptoide-NetworkUtils", "Getting: "+url);

		return bis;

	}
	
	 public static String getFileName(String hash, String type, Context mctx)
	    {
	    	String url = ApplicationYMAX.DEFAULTWEBSERVIC +  "webservices/getXmlName/" + hash + "/" + type;
	    	try {
	    		NetworkUtils utils = new NetworkUtils();
	    		JSONObject json = utils.getJsonObject(url, mctx);
	    		if(json.getString("fileName") != null && !"".equals(json.getString("fileName")))
	    		{
	    			return json.getString("fileName");
	    		}
	    		else
	    		{
	    			return null;
	    		}
	    	}
	    	catch(Exception ex)
	    	{
	    		ex.printStackTrace();
	    		return null;
	    	}
	    }
	

	public static void setTimeout(int timeout){
		NetworkUtils.TIME_OUT=timeout;
	}


	public JSONObject getJsonObject(String url, Context mctx) throws IOException, JSONException{
		String line = null;
		BufferedReader br = new BufferedReader(new java.io.InputStreamReader(getInputStream(url, null, null, mctx)));
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null){
			sb.append(line + '\n');
		}

		return new JSONObject(sb.toString());

	}

	public static boolean isConnectionAvailable(Context context){
		ConnectivityManager connectivityState = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean connectionAvailable = false;
		try {
			connectionAvailable = connectivityState.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED;
			Log.d("ManagerDownloads", "isConnectionAvailable mobile: "+connectionAvailable);
		} catch (Exception e) { }
		try {
			connectionAvailable = connectionAvailable || connectivityState.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED;
			Log.d("ManagerDownloads", "isConnectionAvailable wifi: "+connectionAvailable);
		} catch (Exception e) { }
		try {
			connectionAvailable = connectionAvailable || connectivityState.getNetworkInfo(6).getState() == NetworkInfo.State.CONNECTED;
			Log.d("ManagerDownloads", "isConnectionAvailable wimax: "+connectionAvailable);
		} catch (Exception e) { }
		try {
			connectionAvailable = connectionAvailable || connectivityState.getNetworkInfo(9).getState() == NetworkInfo.State.CONNECTED;
			Log.d("ManagerDownloads", "isConnectionAvailable ethernet: "+connectionAvailable);
		} catch (Exception e) { }

		return connectionAvailable;
	}

    public long getLastModified(URL url) throws IOException {

        return url.openConnection().getLastModified();

    }


}
